package com.sunshine.spring.jdbc.template;

import com.sunshine.spring.jdbc.model.Customer;
import com.sunshine.spring.jdbc.model.CustomerRowMapper;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 客户类Dao实现
 *
 * @Author: WeiHong
 * @Date: 2017/3/16 14:22
 */
public class CustomerDaoImpl extends JdbcDaoSupport implements ICustomerDao {


    @Override
    public void insert(Customer customer) {
        String sql = "INSERT INTO CUSTOMER (CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
        super.getJdbcTemplate().update(sql, new Object[]{customer.getCustId(), customer.getName(), customer.getAge()});
    }

    @Override
    public Customer findByCustomerId(int custId) {
        String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = ?";
        Customer customer = (Customer) super.getJdbcTemplate().queryForObject(sql, new Object[]{custId}, new CustomerRowMapper());
        return customer;
    }

    @Override
    public Customer findByCustomerId2(int custId) {
        String sql = "SELECT CUST_ID, NAME, AGE FROM CUSTOMER WHERE CUST_ID = ?";
        Customer customer = super.getJdbcTemplate().queryForObject(sql, new Object[]{custId}, new BeanPropertyRowMapper<>(Customer.class));
        return customer;
    }

    @Override
    public String findCustomerNameByID(int custId) {
        final String sql = "SELECT NAME FROM CUSTOMER WHERE CUST_ID = ?";
        String s = super.getJdbcTemplate().queryForObject(sql, new Object[]{custId}, String.class);
        return s;
    }

    @Override
    public List<Customer> findAll() {
        String sql = "SELECT * FROM CUSTOMER";
        List<Customer> customers = new ArrayList<>();
        List<Map<String, Object>> rows = super.getJdbcTemplate().queryForList(sql);
        for (Map<String, Object> row : rows) {
            Customer customer = new Customer(
                    Integer.parseInt(row.get("CUST_ID").toString()),
                    row.get("NAME").toString(),
                    Integer.parseInt(row.get("AGE").toString())
            );
            customers.add(customer);
        }
        return customers;
    }



    /*在继承JdbcDaoSupport类中已定义final的setDataSource方法*/
    //public void setDataSource(DataSource dataSource) {
    //    this.dataSource = dataSource;
    //}
}
